package com.ruoyi.factorydata.service.impl;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.factorydata.domain.*;
import com.ruoyi.factorydata.domain.dto.ReportStatisticsSumDTO;
import com.ruoyi.factorydata.mapper.*;
import com.ruoyi.factorydata.service.IWorkOrderLogService;
import com.ruoyi.factorydata.service.IWorkReportService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 报工记录Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-28
 */
@Service
public class WorkReportServiceImpl extends ServiceImpl<WorkReportMapper, WorkReport> implements IWorkReportService {
    @Autowired
    private WorkReportMapper workReportMapper;

    @Autowired
    private ProjectProductionPlanMapper projectProductionPlanMapper;

    @Autowired
    private WorkOrderInfoMapper workOrderInfoMapper;

    @Autowired
    private EquipmentDataMapper equipmentDataMapper;

    @Autowired
    private StationDataMapper stationDataMapper;

    @Autowired
    private IWorkOrderLogService workOrderLogService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询报工记录
     *
     * @param id 报工记录主键
     * @return 报工记录
     */
    @Override
    public WorkReport selectWorkReportById(Long id) {
        return workReportMapper.selectWorkReportById(id);
    }

    @Override
    public List<WorkReport> getListByWorkOrderId(Long workOrderId) {
        return workReportMapper.getListByWorkOrderId(workOrderId);
    }

    /**
     * 查询报工记录列表
     *
     * @param workReport 报工记录
     * @return 报工记录
     */
    @Override
    public List<WorkReport> selectWorkReportList(WorkReport workReport) {
        HashMap<Long, String> nameCache = new HashMap<>();
        List<WorkReport> workReports = workReportMapper.selectWorkReportList(workReport);
        workReports.forEach(item -> {
            String createByName = sysUserService.getUserNameByIdAndCache(Long.parseLong(item.getCreateBy()), nameCache);
            item.setCreateByName(createByName);
            WorkOrderInfo workOrderInfo = workOrderInfoMapper.selectWorkOrderInfoById(item.getWorkOrderId());
            item.setProductionLineId(workOrderInfo.getProductionLineId());
            item.setProductionLineName(workOrderInfo.getProductionLineName());
            item.setBatchNum(workOrderInfo.getBatchNum());
            if (item.getEquipmentId() != null) {
                EquipmentData equipmentData = equipmentDataMapper.selectById(item.getEquipmentId());
                if (equipmentData != null) {
                    item.setEquipmentId(equipmentData.getId());
                    item.setEquipmentName(equipmentData.getEquipmentName());
                }
            }
            if (item.getStationId() != null) {
                StationData stationData = stationDataMapper.selectById(item.getStationId());
                if (stationData != null) {
                    item.setStationId(stationData.getId());
                    item.setStationName(stationData.getName());
                }
            }
        });
        return workReports;
    }

    /**
     * 新增报工记录
     *
     * @param workReport 报工记录
     * @return 结果
     */
    @Override
    @Transactional
    public int insertWorkReport(WorkReport workReport) {
        Assert.notNull(workReport, "报工记录不能为空");
        Assert.notNull(workReport.getWorkOrderId(), "工单id不能为空");
        WorkOrderInfo workOrderInfo = workOrderInfoMapper.selectWorkOrderInfoById(workReport.getWorkOrderId());
        Assert.notNull(workOrderInfo, "工单不存在");
        //查询项目计划信息，拿到项目将产品id
        if (workOrderInfo.getPlanId() != null) {
            ProjectProductionPlan projectProductionPlan = projectProductionPlanMapper.selectById(workReport.getPlanId());
            workReport.setProjectProductionId(projectProductionPlan.getId());
        }
        workReport.setCreateTime(DateUtils.getNowDate());
        int save = workReportMapper.insertWorkReport(workReport);
        if (save > 0) {
            String technicalParameter = workReport.getTechnicalParameter();
            String collect = null;
            if (StringUtils.isNotBlank(technicalParameter)) {
                JSONArray params = JSONArray.parseArray(technicalParameter);
                //转成key=value的字符串 ,{\"name\":\"额外参数\",\"value\":\"111\"}
                collect = params == null || params.isEmpty() ? null : params.stream()
                        .map(obj -> {
                            JSONObject jsonObject = (JSONObject) obj;
                            String name = jsonObject.getString("name");
                            String value = jsonObject.getString("value");
                            return name + "=" + value;
                        })
                        .collect(Collectors.joining(","));
            }
            String equipmentName = null;
            if (workReport.getEquipmentId() != null) {
                EquipmentData equipmentData = equipmentDataMapper.selectEquipmentDataById(workReport.getEquipmentId());
                equipmentName = Optional.ofNullable(equipmentData).map(EquipmentData::getEquipmentName).orElse(null);
            }
            StringBuilder log = new StringBuilder();
            log.append("工单工序：").append(workOrderInfo.getNowProcessName()).append("报工，");
            if (StringUtils.isNotBlank(equipmentName)) {
                log.append("设备：").append(equipmentName).append(",");
            }
            log.append("产出：").append(workReport.getProductionQuantity()).append(",");
            log.append("报废：").append(workReport.getScrapQuantity());
            if (StringUtils.isNotBlank(collect)) {
                log.append("参数：").append(collect);
            }
            workOrderLogService.saveLog(workOrderInfo, log.toString());
        }
        return save;
    }

    /**
     * 修改报工记录
     *
     * @param workReport 报工记录
     * @return 结果
     */
    @Override
    public int updateWorkReport(WorkReport workReport) {
        workReport.setUpdateTime(DateUtils.getNowDate());
        return workReportMapper.updateWorkReport(workReport);
    }

    /**
     * 批量删除报工记录
     *
     * @param ids 需要删除的报工记录主键
     * @return 结果
     */
    @Override
    public int deleteWorkReportByIds(Long[] ids) {
        int i = workReportMapper.deleteBatchIds(Arrays.stream(ids).collect(Collectors.toList()));
        return i;
    }

    /**
     * 删除报工记录信息
     *
     * @param id 报工记录主键
     * @return 结果
     */
    @Override
    public int deleteWorkReportById(Long id) {
        return workReportMapper.deleteWorkReportById(id);
    }

    @Override
    public ReportStatisticsSumDTO getReportStatisticsSum(WorkReport workReport) {
        return workReportMapper.getReportStatisticsSum(workReport);
    }
}